package com.thinkSoft.Location.Activities;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.thinkSoft.Location.R;
import com.thinkSoft.Location.Helpers.Debugger;
import com.thinkSoft.Location.Helpers.EulaCheck;
import com.thinkSoft.Location.Lib.DataFunc;
import com.thinkSoft.Location.Lib.LocalDatabase;
import com.thinkSoft.Location.Lib.WebData;

public class UILogin extends Activity {
	public static final String PREFS_NAME = "LocationApp";
	private static String KEY_SUCCESS = "success";
	private static String KEY_ERROR_MSG = "error_msg";
	private static String KEY_UID = "uid";
	private static String KEY_NAME = "name";
	private static String KEY_EMAIL = "email";
	private static String KEY_CREATED_AT = "created_at";
	private Debugger debug = new Debugger(this);
	public final static String INTENT_ID="com.thinkSoft.Location.Registered";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		checkLogin();
		new EulaCheck(this).show(); 
		setContentView(R.layout.activity_uilogin);
		TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
		Button loginButton = (Button) findViewById(R.id.login_btnlog);

		Bundle extras = getIntent().getExtras();
		if (extras != null){
			if (extras.getBoolean(INTENT_ID, false)){
				new AlertDialog.Builder(this).setTitle("Success!").setMessage("Registration successful.").setNeutralButton("Close", null).show();
			} 
		}

		loginButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				EditText txtUser = (EditText) findViewById(R.id.login_username);
				EditText txtPass = (EditText) findViewById(R.id.login_password);
				if (!WebData.isNetworkAvailable(UILogin.this)){
					debug.postLog(Log.DEBUG, "Login", "No data connection");
					new AlertDialog.Builder(UILogin.this).setTitle("Error").setMessage("No available internet connection.").setNeutralButton("Close", null).show(); 
				}
				else if (txtUser.getText().toString().equals("") || txtPass.getText().toString().equals("")){
					debug.postLog(Log.DEBUG, "Login", "Input error");
					new AlertDialog.Builder(UILogin.this).setTitle("Error").setMessage("Please verify your inputs and try again.").setNeutralButton("Close", null).show(); 
				}
				else{
					new LoginCheck(UILogin.this).execute();
				}

			}
		});
		registerScreen.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), UIRegister.class);
				startActivity(i);
				finish();
			}
		});
	}

	private void checkLogin() {
		DataFunc userDb = new DataFunc();
		if(userDb.isUserLoggedIn(getApplicationContext())){
			// user is not logged in show login screen
			Intent login = new Intent(getApplicationContext(), UIDashboard.class);
			login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(login);
			// Closing dashboard screen
			finish();            
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_uilogin, menu);
		return true;
	}

	public class LoginCheck extends AsyncTask < String , Context , Void > {
		private ProgressDialog progressDialog ;
		private Context targetCtx ;
		private Boolean logIn = false;
		private String response = "";
		public LoginCheck ( Context context ) {
			this.targetCtx = context ;
			progressDialog = new ProgressDialog ( targetCtx ) ;
			progressDialog.setCancelable ( false ) ;
			progressDialog.setMessage ( "Contacting Server..." ) ;
			progressDialog.setTitle ( "Please wait" ) ;
			progressDialog.setIndeterminate ( true ) ;
		}

		@ Override
		protected void onPreExecute ( ) {
			progressDialog.show ( ) ;
		}

		@ Override
		protected Void doInBackground ( String ... params ) {
			EditText username = (EditText) findViewById(R.id.login_username);
			EditText password = (EditText) findViewById(R.id.login_password);
			progressDialog.setMessage("Checking login...");
			DataFunc userFunction = new DataFunc();
			JSONObject json = userFunction.loginUser(username.getText().toString(), password.getText().toString());

			// check for login response
			try {
				if (json.getString(KEY_SUCCESS) != null) {

					String res = json.getString(KEY_SUCCESS);
					if(Integer.parseInt(res) == 1){
						// user successfully logged in
						// Store user details in SQLite Database
						LocalDatabase db = new LocalDatabase(getApplicationContext());
						JSONObject json_user = json.getJSONObject("user");

						// Clear all previous data in database
						userFunction.logoutUser(getApplicationContext());
						db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));                        
						logIn = true;

					}else{
						// Error in login
						response = json.getString(KEY_ERROR_MSG);
					}
				}
			} catch (JSONException e) {
				//e.printStackTrace();
			}
			return null;
		}

		@ Override
		protected void onPostExecute ( Void result ) {
			if(progressDialog != null && progressDialog.isShowing()){
				progressDialog.dismiss ( ) ;
				if (logIn){
					Intent i = new Intent(getApplicationContext(), UIDashboard.class);
					i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
					finish();
				}
				else{
					new AlertDialog.Builder(targetCtx).setTitle("Error").setMessage(response).setNeutralButton("Close", null).show();                 	
				}
			}
		}
	}
}
